<script setup>
import { useStore } from 'vuex';
import { useRoute, onBeforeRouteUpdate } from 'vue-router';
import SortButton from '@/components/sort-button/index.vue';

const route = useRoute();
const store = useStore();

const currentPage = ref(1);

const params = {
  brandId: undefined,
  attrs: [],
  page: currentPage.value,
  pageSize: 10,
  categoryId: route.params.id,
};

function init(to) {
  params.categoryId = to.params.id;
  store.dispatch('goods/resetSubCategoryGoods', params);
  store.dispatch('goods/updateSubCategoryFilter', to.params.id);
}

// 初始化请求
init(route);
// 路由守卫
// 路由id变化时, 重新请求
onBeforeRouteUpdate(init);

const subCategoryGoods = computed(() => store.state.goods.subCategoryGoods);

// 记录
let observer = null;
let lastObserver = null;

const hasNext = computed(() => subCategoryGoods.value.pages > currentPage.value);

watch(subCategoryGoods, async () => {
  if (!hasNext.value) {
    return;
  }
  await nextTick();
  // 取消上一轮的观察
  if (observer) {
    observer.unobserve(lastObserver);
  }
  // 当clothes滚动到视野中时, dispatch
  observer = new IntersectionObserver(
    (entries) => {
      if (entries[0].isIntersecting) {
        // 应该自己写的内容
        params.page = ++currentPage.value;
        store.dispatch('goods/updateSubCategoryGoods', params);
      }
    },
    {
      root: null,
      rootMargin: '0px',
      threshold: 0.5,
    },
  );
  lastObserver = document.querySelector('.item:last-child');
  // 启动观察clothes.value是否进入视野
  observer.observe(lastObserver);
});

// 引入名为subCategoryFilters的getters
const subCategoryFilters = ref([]);
const subCategoryFiltersAttrs = ref([]);

watch(
  () => store.getters['goods/subCategoryFilters'],
  () => {
    subCategoryFilters.value = store.getters['goods/subCategoryFilters'].map((d) => ({
      ...d,
      properties: [
        {
          id: 'all',
          name: '全部',
        },
        ...d.properties,
      ],
    }));
    subCategoryFiltersAttrs.value = store.getters['goods/subCategoryFilters'].map((d) => ({
      groupName: d.name,
      propertyName: '全部',
    }));
  },
);

// 点击某一个筛选器时
async function onFilterChange() {
  await nextTick();
  const attrs = subCategoryFiltersAttrs.value.filter((d, i) => d.propertyName !== '全部' && i > 0);
  currentPage.value = 1;
  params.brandId = store.state.goods.subCategoryFilter.brands.find((b) => b.name === subCategoryFiltersAttrs.value[0].propertyName)?.id || null;
  params.attrs = attrs;
  params.page = 1;
  store.dispatch('goods/resetSubCategoryGoods', params);
}

const sortType = ref('');

function onSortChange(value) {
  sortType.value = value;
}

</script>

<template>

  <el-form>
    <el-form-item v-for="(item, i) in subCategoryFilters" :key="item.id" :label="item.name">
      <el-radio-group v-model="subCategoryFiltersAttrs[i].propertyName" @change="onFilterChange">
        <el-radio v-for="property in item.properties" :key="property.id" :label="property.name">
          {{ property.name }}
        </el-radio>
      </el-radio-group>
    </el-form-item>
  </el-form>

  <!-- <sort-button
    :value="sortType"
    @change="onSortChange"
  >
    价格排序
  </sort-button> -->

  <sort-button v-model:value="sortType">
    价格排序
  </sort-button>

  <ol class="container">
    <li class="item" v-for="item in subCategoryGoods.items" :key="item.id">
      {{ item.name }}
    </li>
  </ol>
  <div v-if="!hasNext">没有更多了</div>
</template>

<style lang="scss" scoped>
ol {
  margin-left: 50px;

  li {
    font-size: 50px;
    padding: 20px;
  }
}
</style>
